package com.xysoft.admin.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.xysoft.admin.common.ElementConst;
import com.xysoft.admin.dto.ConfigDTO;
import com.xysoft.admin.service.IConfigService;
import com.xysoft.model.Config;
import com.xysoft.util.JsonUtil;
import com.xysoft.util.RequestUtil;

@Component
@SuppressWarnings("unchecked")
public class ConfigServiceImpl extends BaseServiceImpl implements IConfigService {

	@Transactional
	public String get() {
		List<Config> cfgs = this.getBaseDao().find("from Config order by id desc");
		List<ConfigDTO> dtos = new ArrayList<ConfigDTO>();
		for (Config cfg : cfgs) {
			ConfigDTO dto = new ConfigDTO();
			BeanUtils.copyProperties(cfg, dto);
			dtos.add(dto);
		}
		return JsonUtil.toString(dtos);
	}

	@Transactional
	public Map<String, Object> edit(HttpServletRequest request) {
		String value = RequestUtil.getValue(request, "value");
		int id = Integer.valueOf(RequestUtil.getValue(request, "id"));
		Config cfg = (Config)this.getBaseDao().get(Config.class, id);
		cfg.setValue(value);
		this.getBaseDao().save(cfg);
		ElementConst.setValue(cfg.getKeyName(), value);
		Map<String, Object> modelMap = new HashMap<String,Object>(2);
		modelMap.put("success", true);
		modelMap.put("msg", "保存成功！");
		return modelMap;
	}

}
